#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* p1 = l1;
    ListNode* p2 = l2;
    ListNode* p = new ListNode(0,nullptr);
    ListNode* head = p;
    int cnt = 1;
    int tag=0;
    while(p1 != nullptr && p2 != nullptr){
        p->val = (tag + p1->val + p2->val) % 10;
        tag = (tag + p1->val + p2->val) / 10;
        p1 = p1->next;
        p2 = p2->next;
        p->next = new ListNode(0,nullptr);
        cnt++;
        p = p->next;
    }

    if(p1 == nullptr){
        while(p2 != nullptr){
            p->val = (tag + p2->val) % 10;
            tag = (tag + p2->val) / 10;
            p2 = p2->next;
            p->next = new ListNode(0,nullptr);
            cnt++;
            p = p->next;
        }
        if(tag == 1){
            p->val = 1;
            return head;
        }
    }else{
        while(p1 != nullptr){
            p->val = (tag + p1->val) % 10;
            tag = (tag + p1->val) / 10;
            p1 = p1->next;
            p->next = new ListNode(0,nullptr);
            cnt++;
            p = p->next;
        }
        if(tag == 1){
            p->val = 1;
            return head;
        }
    }

    p = head;
    for(int i=1;i<=cnt-2;i++) p = p->next;
    p->next = nullptr;
    return head;
}